/***************************************************************************
 *   Copyright (C) 2008 by Ryszard Krol   *
 *   rysiek.krol@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "picturelistwidgetitem.h"
#include <QDir>
#include <zlib.h>
#include <QDateTime>
#include <QTextCodec>


/**
* Kostruktor Klasy
*/
PictureListWidgetItem::PictureListWidgetItem ( QFileInfo & fileInfo,
        QListWidget * parent )
		: QListWidgetItem ( parent )
{
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	this->file =  fileInfo;
	this->commentString.clear();
	this->getDescription ( fileInfo );
	this->generateLabel();
}


/**
* Destruktor Klasy
*/
PictureListWidgetItem::~PictureListWidgetItem()
{
}


QIcon PictureListWidgetItem::generateIcon ( const QFileInfo  &filePatch )
{

	QIcon result;

	if ( filePatch.isFile() )
	{
		QImage image ( filePatch.filePath() );
		image = image.scaled ( QSize ( 150,150 ) );
		QPixmap pixmap = pixmap.fromImage ( image );
		result.addPixmap ( pixmap );
	}
	return result;
}


void PictureListWidgetItem::getDescription ( const QFileInfo & fileInfo )
{
	QFileInfo *descFile;
	QString dane = "";
	QDir commentDir ( fileInfo.dir() );
	this->commentString.clear();
	if ( commentDir.cd ( ".comments" ) )
	{
		descFile = new QFileInfo ( commentDir.absoluteFilePath (fileInfo.fileName() ) +".xml" );
		if ( descFile->exists() && !fileInfo.isDir())
		{
			if ( this->unGzip ( descFile, &dane ) )
			{
				this->commentString = dane;
				//Wyciaganie komentarza
				QString tekst = dane.section ("<Note>",1,1);
				tekst = tekst.section("</Note>", 0,0);
				this->note = tekst;
				
				//Wyciaganie miejsca
				tekst = dane.section("<Place>",1,1);
				tekst = tekst.section("</Place>",0,0);
				this->place = tekst;
					
				//Wyciąganie czasu
				tekst = dane.section("<Time>",1,1);	
				tekst = tekst.section("</Time>",0,0);
				if (tekst != ""){
 				this->time.setTime_t(tekst.toUInt());
				}
				
			} else {
				this->commentString.clear();
			}
		} else {
			this->commentString.clear();
		}
		delete descFile;
	}
	else
	{
		dane = fileInfo.fileName();
		this->commentString.clear();
	}
}

/**
* Rozpakowuje plik 
* @param QFileInfo - Plik do rozpakowania
* @param QString - Wskaźnik do QStringa do którego chemy rozpakowac plik
*/
int PictureListWidgetItem::unGzip ( QFileInfo *fileInfo, QString *dest )
{
	char buf[1024];
	gzFile pliczek;
	int res = 0;
	const char *fileName;
	QByteArray array = fileInfo->filePath().toLocal8Bit();
	fileName = array.data();
	pliczek = gzopen ( fileName, "rb" );
	res = gzread ( pliczek, buf, 1024 );
	gzclose(pliczek);
	*dest = buf;
	this->textConverter(dest);
	return res;
}

/**
* Generuje Opis i ToolTipa z danymi zdjęcia
*/
void PictureListWidgetItem::generateLabel(){
	
	QString opis;
	QString toolTip;
	if (this->file.isDir()){
			
	opis =this->file.fileName();

	} else {
		toolTip = QObject::tr("Picture data: ");
		toolTip.append("\n" + QObject::tr("File Name: ") + this->file.fileName());
	if (this->note != ""){
		toolTip.append("\n" + QObject::tr("Comment: ") + this->note);
	}
	if (this->place != ""){
		toolTip.append("\n" + QObject::tr("Place: ") + this->place);
		opis.append(this->cutString(this->place));
	}
	if (this->time.isValid() && this->time.toTime_t()!=0){
		toolTip.append("\n" + QObject::tr("Time: ") + this->time.toString());
		opis.append("\n" + this->time.date().toString());
		opis.append("\n" + this->time.time().toString());
		
	}
	}
	if (opis == ""){
		opis = this->cutString(this->file.fileName());
		this->setText(opis);

	}else {
		this->setText(opis);
		
		
	}
	if(!toolTip.isEmpty()) {
		this->setToolTip(toolTip);
	}
}

/**
* Set's Icon to the Item
*/
void PictureListWidgetItem::putIcon(){
	this->setIcon ( this->generateIcon ( this->file ) );
}

/**
* Returns comment's Note field
*/
QString PictureListWidgetItem::getNote() const
{
	return note;
}

bool PictureListWidgetItem::isDate(){
	
	
	return !this->time.isNull();
}


void PictureListWidgetItem::setNote ( const QString& theValue )
{
	note = theValue;
}


QString PictureListWidgetItem::getPlace() const
{
	return place;
}

/**
* Ustawia komentaz "miejsce"
*/
void PictureListWidgetItem::setPlace ( const QString& theValue )
{
	place = theValue;
}

/**
* Zwraca Plik klasy
* @return QFileInfo - zwraca plik do którego odnosi się plik
*/
QFileInfo  PictureListWidgetItem::getFile() 
{
	return this->file;
}

/**
* Ustawia plik w klasie
* @param QFileInfo - plik do którego ta klasa ma się odnosić
*/
void PictureListWidgetItem::setFile ( const QFileInfo& theValue )
{
	file = theValue;
}

/**
* Zwraca Czas zrobienia zdjęcia
* @return QDateTime - Data zrobienia zdjęcia
*/
QDateTime PictureListWidgetItem::getDateTime(){
	return this->time;

}

/**
* Konwetruje QString zapewniając poprawne wyświetlanie polskich znaków
*/
void PictureListWidgetItem::textConverter(QString *text){
	
	text->replace("&#xF3;", "ó");
	text->replace("&#x142;", "ł");
	text->replace("&#x15A;", "Ś");
	text->replace("&#x15B;", "ś");
	text->replace("&#x17C;", "ż");
	text->replace("&#x119;", "ę");
	text->replace("&#x144;", "ń");	
	
}

/**
* Zwraca commentString
* @return QString - string zawiera komentarz XML'owy
*/
QString PictureListWidgetItem::getCommentString() const
{
        return commentString;
}

/**
* Formatuje String do wyświetlania w broswerWidgecie
*/
QString PictureListWidgetItem::cutString(QString string)
{
        if (string.size()>20) {
        	if (string.lastIndexOf(" ", 20)>0) return string.replace(string.lastIndexOf(" ", 25), 1, "\n");
        	string.chop((20 - string.size())*(-1));
        	string = string.append("...");

        }
        return string;

}
